    export default {
        name: "cxjg",
        setup(props) {
            const router = VueRouter.useRouter();
            const route = VueRouter.useRoute();
            const configs = inject('globalConfigs');
            const { smartSpeak } = inject('speech'); //语音
            const lastpage = ref();
            const id = ref('');
            const zd = ref({});
            const bgsx = ref({});
            const cxjgs = ref({});
            const pageSize = ref(10); // 每页数据量
            const pageCurrent = ref(1); // 当前页
            const total = ref(0); // 数据总量
            const current = ref(0);
            const option = ref({url: '', name: 'file'});
            const jsonkeys = ref(['muselect', 'checkbox', 'multiimage', 'subtable', 'multifile', 'video', 'area']);
            const showPagination = computed(()=>{  
                return total.value > pageSize.value;
            });
            const printDialogVisible = ref(false); //打印相关
            const currentPrintContent = ref('');
            const printType = ref('');
            const printContent = ref(null);
            const docxContainer = ref(null);
            const errorMessage = ref('');
            const loading = ref(false);
            const isContentLoaded = ref(false);
            const dialogkb = ref(false);
        	const kbcloums = ref({});
        	const kbdata = ref([]);//子表数据详情
            const dialogfwb = ref(false);
            const fwbtxt = ref('');	
            const dialogmap = ref(false);
            const videourl = ref();
            const videoDialogVisible = ref(false); 
            const videoPlayer = ref(null);
            
            const isedit = computed(()=>{  
                return total.value > 0 && bgsx.value && typeof bgsx.value.fields === 'object' && bgsx.value.fields !== null && bgsx.value.kftb?.length;
            });
            
            // 动态列处理
            const columns = computed(() => {
                if (!bgsx.value?.fields) return {};
                return Object.entries(bgsx.value.fields).reduce((acc, [key, field]) => {
                    if (bgsx.value.kfcx?.includes(key)) {
                        acc[key] = field.name;
                    }
                    return acc;
                }, {});
            });

            onMounted(async() => {
                if (!route.query.data) {
                    smartSpeak('参数不正确，请返回');
                	ElMessage.error('参数不正确，请返回');
        			setTimeout(() => {
        				router.push({name: 'home'});
        			}, 1500);
                } else {
                    lastpage.value = JSON.parse(decodeURIComponent(route.query.data));
                    id.value = lastpage.value.id;
                	getcxjg();
                }
            });
            
			const toaddform = (rowid) => {
                router.push({
                    name: 'formedit', 
                    params: {tableid: bgsx.value.id, rowid: rowid},
                    query: { data: encodeURIComponent(JSON.stringify({})) }
                });
			}
            
            // 查询不到时：如果开启了唯一填报，有查询结果时会自动进入修改界面，没查询结果时自动进入新建填报。如果没开启唯一填报，有查询结果时可选择新建或修改，没查询结果时自动进入新建填报。
			const handleQueryNotFound = (msg, rowid) => {
				setTimeout(() => {
				    if (bgsx.value.kftb?.length > 0) {
                        toaddform(rowid);
				    }else{
        			    smartSpeak(msg);
        				ElMessage.error(msg);
                        router.back();
                    }
				}, 600);
			}
            
        	// 查询结果
            const getcxjg = _.debounce(async (currentPage = 1) => {
                pageCurrent.value = currentPage;
                const input = { ...lastpage.value };
                delete input.id;
                if (Object.keys(input).length === 0) {
                    smartSpeak('输入为空');
                    return ElMessage.error('输入为空');
                }
                const res = await cxjgapi({id: id.value,input,page: pageCurrent.value,pageSize: pageSize.value});
                bgsx.value = res.bgsx;
                if (Number(res.total) < 1) {
                    handleQueryNotFound('没有查找到，请检查输入', 0);
        			return;
                }
                zd.value = Object.entries(bgsx.value.fields).reduce((acc, [key, field]) => {
                    acc[key] = field.name;
                    return acc;
                }, {});
                const jsonTypes = new Set(jsonkeys.value);
                res.items.forEach(item => {
                    processJsonFields(item, bgsx.value.fields, jsonTypes);
                });
                cxjgs.value = res.items.map(item => ({ ...item }));
                total.value = res.total;
            }, 300);
            
            // 处理 JSON 字段
			const processJsonFields = (item, fields, jsonTypes) => {
				for (const [key, field] of Object.entries(fields)) {
					if (jsonTypes.has(field.type)) {
						const value = item[key];
						item[key] = value && window.validators.isJSON(value) ? JSON.parse(value) : [];
					}
				}
			}
            
			//锁定查询
			const locke = async (id) => {
				if(!id) return;
                try {
                    const { value } = await ElMessageBox.confirm(
                        '锁定后该条数据无法再查询。',
                        '确认要锁定？',
                        {confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning'}
                    );
                    // 如果用户点击确认
                    let input = { ...lastpage.value };
                    delete input.id;
                    await lockeapi({ id: id.value, tablename: bgsx.value.tablename, input });
                    ElMessage.success('锁定成功');
                } catch (error) {
                    if (error === 'cancel') {
                        ElMessage.info('操作已取消');
                    }
                }
			};

			// 分页触发
			const change = (e) => {
				getcxjg(e.current);
			};

			const checkImgType = (fileName) => {
				if (!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileName) && !window.validators.isBase64Image(fileName)) {
					return false;
				} else {
					return true;
				}
			};

            // 列宽计算
            const getColumnWidth = (key) => {
                const fieldType = bgsx.value.fields[key]?.type;
                const defaultWidths = {
                    image: 120,
                    file: 120,
                    muselect: 180,
                    checkbox: 180,
                    multifile: 200,
                    idcard: 180,
                    multiimage: 200,
                    area: 180,
                    date: 150,
                    mobile: 120,
                    datetime: 180,
                    text: 180,
                    textarea: 240,
                    sczs: 200,
                };
                return defaultWidths[fieldType] || 'auto';
            };
            
            // 跳转编辑已填数据，为防止篡改id，加入查询条件
            const toggleEdit = (row) => {
                let tid = row.ID || null;
                let input = { ...lastpage.value };
                delete input.id;
                router.push({
                    name: 'formedit', 
                    params: { tableid: id.value, rowid: tid },
                    query: { data: encodeURIComponent(JSON.stringify(input)) }
                });
            }
            
            //查看子表
            const ckzb = (k, value) => {
                if(!k || !value) return;
                if(value.length > 0){
                    kbcloums.value = {};
                    let xx = bgsx.value.fields[k].zboptions.map(item => { return item.key });
                    for(let v of xx){
                        kbcloums.value[v] = v;
                    }
                    kbdata.value = value;
                    dialogkb.value = true;
                }
            }
            
            //查看富文本
            const ckfwb = (v) => {
                if(!v) return;
                fwbtxt.value = v;
                dialogfwb.value = true;
            }
                
            const toback = () => {
                router.back();
            }
            
            // 打印
            const handlePrint = async (content, type) => {
            	try {
            		errorMessage.value = '';
            		currentPrintContent.value = content;
            		printType.value = type;
            		isContentLoaded.value = false;
            		loading.value = true;
            		// 先重置容器引用
            		docxContainer.value = null
            		// 分步打开弹窗
            		printDialogVisible.value = true
            		await nextTick() // 等待弹窗开始渲染
            		// 添加双重等待确保DOM更新
            		await new Promise(resolve => {
            			setTimeout(() => {
            				requestAnimationFrame(resolve)
            			}, 500)
            		})
            		if (type === 'word') {
                		// 强制获取容器引用
                		if (!docxContainer.value) {
                			docxContainer.value = document.querySelector('.docx-preview')
                		}
                		validateContainer();
            			// 获取文档内容
            			const response = await fetch(content);
            			if (!response.ok) throw new Error('文档加载失败');
            			const arrayBuffer = await response.arrayBuffer();
            			// 清空容器
            			docxContainer.value.innerHTML = '';
            			// 渲染文档
            			const res = await docx.renderAsync(
            				arrayBuffer,
            				docxContainer.value,
            				null, {
            					className: "docx", // 默认样式类名
            					inWrapper: false, // 禁用自带容器
            					ignoreWidth: false,
            					ignoreHeight: false,
            					breakPages: true
            				}
            			);
            			// 添加打印样式
            			const style = document.createElement('style');
            			style.innerHTML = `
            	.docx-wrapper {
            	  background: white !important;
            	  padding: 20px !important;
            	}
            	.docx > section {
            	  margin: 0 auto !important;
            	  max-width: 8.5in !important;
            	}
              `;
            			docxContainer.value.appendChild(style);
            		}
            
            		loading.value = false;
            		isContentLoaded.value = true;
            	} catch (error) {
            		console.error('预览失败:', error);
            		loading.value = false;
            		errorMessage.value = `文档预览失败：${error.message}`;
            	}
            };
            
            const doPrint = () => {
            	nextTick(() => {
            		const printWindow = window.open('', '_blank');
            		const content = printContent.value.innerHTML;
            		console.log(content);
            		printWindow.document.write(`
              <html>
            	<head>
            	  <title>打印文档</title>
            	  <style>
            		${docx.defaultStyles}
            		body { margin: 0; }
            		.docx-wrapper {
            		  background: white !important;
            		  padding: 20px !important;
            		}
            		.docx > section {
            		  margin: 0 auto !important;
            		  max-width: 8.5in !important;
            		}
            		@media print {
            		  .docx p {
            			margin: 0 !important;
            		  }
            		  .docx table {
            			page-break-inside: auto !important;
            		  }
            		  .docx tr {
            			page-break-inside: avoid !important;
            		  }
            		}
            	  </style>
            	</head>
            	<body>
            	  ${content}
            	  <script>
            		window.onload = function() {
            		  window.print();
            		  setTimeout(() => window.close(), 1000);
            		}
            	  <\/script>
            	</body>
              </html>
            `);
            		printWindow.document.close();
            	});
            };
            
            const validateContainer = () => {
            	if (!docxContainer.value) {
            		console.error('容器元素状态:', {
            			exists: !!docxContainer.value,
            			visible: docxContainer.value?.offsetParent !== null,
            			dimensions: docxContainer.value?.getBoundingClientRect()
            		})
            		throw new Error('文档容器未找到，当前容器引用: ' + docxContainer.value)
            	}
            }
            
        	//显示地图
            const showMyMap = (string) => {
                if(!string)return;
                dialogmap.value = true;
                setTimeout(() => {
                    let array = string.split(',');
                    //定义地图中心点坐标
                    var center = new TMap.LatLng(array[0],array[1])
                    //定义map变量，调用 TMap.Map() 构造函数创建地图
                    var map = new TMap.Map(document.getElementById('container'), {
                        center: center,//设置地图中心点坐标
                        zoom: 15,   //设置地图缩放级别
                        pitch: 43.5,  //设置俯仰角
                        rotation: 45    //设置地图旋转角度
                    });
                    //标记中心点
                    var markerLayer = new TMap.MultiMarker({
                        map: map,
                        geometries: [{"id": "1","position": center}]
                    });
                }, 500);
            }
                
            watch(printDialogVisible, async (visible) => {
            	if (visible) {
            		await nextTick()
            		if (!docxContainer.value) {
            			docxContainer.value = document.querySelector('.docx-preview')
            			console.warn('自动恢复容器引用:', docxContainer.value)
            		}
            	}
            })
            
            // 关闭窗口要停止视频播放
            watch(() => videoDialogVisible.value, (newValue, oldValue) => {
                    if (!newValue && videoPlayer.value) {
                        videoPlayer.value.pause();
                    }
                }
            );
            
            return {
                configs,
                lastpage,
                id,
                zd,
                bgsx,
                cxjgs,
                pageSize,
                pageCurrent,
                total,
                current,
                option,
                jsonkeys,
                showPagination,
                isedit,
                columns,
                locke,
                getcxjg,
                change,
                checkImgType,
                getColumnWidth,
                toggleEdit,
                toback,
                handlePrint,
                printDialogVisible,
                currentPrintContent,
                printType,
                printContent,
                doPrint,
                docxContainer,
                errorMessage,
                loading,
                isContentLoaded,
                validateContainer,
                ckzb,
                kbdata,
                dialogkb,
                kbcloums,
                processJsonFields,getFileName,toaddform,
                ckfwb,fwbtxt,dialogfwb, dialogmap, videourl, videoDialogVisible, videoPlayer, showMyMap, handleQueryNotFound
            };
        },
        
        template: `
<div v-if="configs.name">
    <el-dialog v-model="dialogmap" title="地图查看">
        <div id="container"></div>
    </el-dialog>
    
    <el-dialog title="预览视频" v-model="videoDialogVisible" top="2vh">
        <video ref="videoPlayer" controls width="100%" :style="{ maxHeight: 'calc(100vh - 100px)' }" :src="videourl" preload="auto" playsinline></video>
    </el-dialog>
    <!-- 查看子表弹窗 -->
    <el-dialog v-model="dialogkb" title="查看子表数据" width="65%" v-if="Object.keys(kbcloums).length > 0 && kbdata.length > 0">
        <div style="height: 400px">
            <el-table :data="kbdata" max-height="550" table-layout="auto" :header-cell-style="{'font-size': '14px',background:'#eff6fa'}" :row-style="{'font-size':'13px'}" border>
                <template v-for="(v, k) in kbcloums" :key="k">
                    <el-table-column :label="v">
                        <template #default="{ row }">
                            <div v-if="typeof row[k] === 'string' && $validators.isJSON(row[k])">多图隐藏</div>
                            <div v-else-if="typeof row[k] === 'string' && $validators.isImageUrl(row[k])">
                                <el-image style="max-width: 80px;height: 30px;" :src="row[k]" :preview-src-list="[row[k]]"></el-image>
                            </div>
                            <div v-else-if="typeof row[k] === 'string' && row[k].startsWith('http')">
                                <a :href="row[k]" target="_blank" rel="noopener noreferrer">{{ $t('download') }}</a>
                            </div>
                            <div v-else>
                                <span>{{ row[k] }}</span>
                            </div>
                        </template>
                    </el-table-column>
                </template>
            </el-table>
        </div>
    </el-dialog>
    
    <!-- 查看富文本弹窗 -->
    <el-dialog v-model="dialogfwb" title="查看内容">
        <div v-html="fwbtxt"></div>
    </el-dialog>

    <!-- 打印弹窗 -->
    <el-dialog v-model="printDialogVisible" title="打印预览" class="print-preview-dialog" :append-to-body="true" :destroy-on-close="false">
    	<div ref="printContent" v-loading="loading">
    		<!-- 图片预览 -->
    		<img v-if="printType === 'image'" :src="currentPrintContent" style="max-width: 100%" />
    		<!-- Word文档预览 -->
    		<div v-if="printType === 'word'" ref="docxContainer" class="docx-preview"></div>
    		<!-- 加载状态 -->
    		<div v-if="loading" class="loading-wrapper">
    			<el-icon class="is-loading" size="24"><Loading /></el-icon>
    			<span>文档加载中...</span>
    		</div>
    		<!-- 错误提示 -->
    		<div v-if="errorMessage" class="error-message">
    			<el-alert :title="errorMessage" type="error" />
    		</div>
    	</div>
    	<template #footer>
    		<el-button @click="printDialogVisible = false">取消</el-button>
    		<el-button type="primary" @click="doPrint" :disabled="!isContentLoaded">
    			立即打印
    		</el-button>
    	</template>
    </el-dialog>
    
	<div class="header row">
		<div class="col-lg-2 col-md-0">&nbsp;</div>
		<div class="col-lg-10 col-md-12">
			<a href="/pc"><img class="icon-logo" src="/pc_static/logo.png" /></a>
		</div>
	</div>

	<div class="c-center" style="margin-top:30px;">
		<div class="cen-form2">
		    <div class="ckhead">
				<p style="margin: 0; padding: 0;">{{bgsx.formname}}</p>
			</div>
			<div style="padding: 20px; width: 90%; margin: auto;" v-if="bgsx && total > 0">
                <el-table :data="cxjgs" border :row-key="row => row.ID"	:header-cell-style="{ background: '#f9f9f9', fontSize: '14px' }" show-overflow-tooltip>
                
                	<!-- 动态列 -->
                	<template v-for="(colName, colKey) in columns" :key="colKey">
                		<el-table-column :prop="colKey" :label="colName" :width="getColumnWidth(colKey)">
                            <template #header>
                            	<el-tooltip v-if="colName.length > 4" :content="colName">
                            		<span class="column-header">{{ colName }}</span>
                            	</el-tooltip>
                            	<span v-else>{{ colName }}</span>
                            </template>
                
                            <template #default="scope">
                                <span v-if="['muselect','checkbox'].includes(bgsx.fields[colKey]?.type)">
                                    {{ scope.row[colKey].toString() }}
                                </span>
                                <span v-else-if="bgsx.fields[colKey]?.type == 'area'">
                                    {{ scope.row[colKey].join('') }}
                                </span>
                                <!-- 图片类型 -->
                                <el-image v-else-if="bgsx.fields[colKey]?.type === 'image' && scope.row[colKey]" :src="scope.row[colKey]"
                                	:preview-src-list="[scope.row[colKey]]" style="max-width: 80px; cursor: pointer;"
                                	@click="previewImage(scope.row[colKey])">
                                	<template #error>
                                		<div class="image-error">加载失败</div>
                                	</template>
                                </el-image>
                                
                                <!--证书-->
                                <div class="print-container" v-else-if="bgsx.fields[colKey]?.type === 'sczs' && scope.row[colKey]">
                                    <el-image :src="scope.row[colKey]" :preview-src-list="[scope.row[colKey]]" style="max-width: 80px; cursor: pointer;" @click="previewImage(scope.row[colKey])">
                                    	<template #error>
                                    		<div class="image-error">加载失败</div>
                                    	</template>
                                    </el-image>
                                    <el-button size="small" @click="handlePrint(scope.row[colKey], 'image')" class="print-button">
                                        <el-icon><Printer /></el-icon>打印
                                    </el-button>
                                </div>
                                
                                <!--word -->
                                <div class="print-container" v-else-if="bgsx.fields[colKey]?.type === 'word' && scope.row[colKey]">
                                    <el-link type="primary" :href="scope.row[colKey]" target="_blank" :underline="false">
                                		<el-icon><Document /></el-icon>下载文档
                                	</el-link>
                                	<el-button size="small" @click="handlePrint(scope.row[colKey], 'word')" class="print-button">
                                	    <el-icon><Printer /></el-icon>打印
                                	</el-button>
                                </div>
                                
                                <template v-else-if="bgsx.fields[colKey]?.type === 'file'">
                                    <div class="print-container" v-if="scope.row[colKey]">
                                    	<el-link type="primary" :href="scope.row[colKey]" target="_blank" :underline="false">
                                    		{{getFileName(scope.row[colKey])}}
                                    	</el-link>
                                	</div>
                                </template>
                                
                                <template v-else-if="bgsx.fields[colKey]?.type === 'multifile'">
                                	<div class="print-container" v-if="scope.row[colKey]">
                                		<div v-for="(src, idx) in scope.row[colKey]" :key="idx">
                                			<el-link type="primary" :href="src" target="_blank" :underline="false">
                                        		{{getFileName(src)}}
                                        	</el-link>
                                		</div>
                                	</div>
                                </template>
                                
                                <!-- 多图轮播 -->
                                <el-carousel v-else-if="bgsx.fields[colKey]?.type === 'multiimage' && scope.row[colKey]" indicator-position="outside" height="120px">
                                	<el-carousel-item v-for="(img, idx) in scope.row[colKey]" :key="idx">
                                		<el-image :src="img" :preview-src-list="scope.row[colKey]" :initial-index="idx" preview-teleported style="height: 100%"></el-image>
                                	</el-carousel-item>
                                </el-carousel>
                                
                                <!-- 子表 -->
                                <template v-else-if="bgsx.fields[colKey]?.type == 'subtable' && Array.isArray(scope.row[colKey])">
                                	<el-button type="primary" link size="small" @click="ckzb(colKey, scope.row[colKey])">查看内容</el-button>
                                </template>
                                
                                <!-- 地图 -->
                                <template v-else-if="bgsx.fields[colKey]?.type == 'map' && scope.row[colKey]">
                                	<el-button type="primary" link size="small" @click="showMyMap(scope.row[colKey])">查看</el-button>
                                </template>
                                
                                <!-- 视频 -->
                                <template v-else-if="bgsx.fields[colKey]?.type == 'video' && scope.row[colKey]">
                                    <div v-for="item in scope.row[colKey]">
                                        <el-button type="primary" v-if="item" link size="small" @click="videourl = item; videoDialogVisible = true;">查看</el-button>
                                	</div>
                                </template>
                                
                                <!-- 富文本 -->
                                <template v-else-if="bgsx.fields[colKey]?.type == 'richtext' && scope.row[colKey]">
                                	<el-button type="primary" link size="small" @click="ckfwb(scope.row[colKey])">查看内容</el-button>
                                </template>
                                
                                <!-- 普通文本 -->
                                <span v-else>
                                	{{ scope.row[colKey] || '' }}
                                </span>
                			</template>
                		</el-table-column>
                	</template>
                
                	<!-- 操作列 -->
                    <el-table-column fixed="right" label="操作" width="150" v-if="isedit || bgsx.suoding">
                        <template #default="scope">
                        	<div class="action-buttons">
                                <el-button v-if="isedit" size="small" @click="toggleEdit(scope.row)">编辑</el-button>
                                <el-button v-if="bgsx.suoding" type="danger" size="small" @click="locke(scope.row.ID)">锁定</el-button>
                        	</div>
                        </template>
                    </el-table-column>
                </el-table>
                
                <!-- 分页 -->
                <div v-if="showPagination" class="pagination-container">
                	<el-pagination background layout="total, sizes, prev, pager, next" :total="total"
                		v-model:current-page="pageCurrent" v-model:page-size="pageSize" @current-change="getcxjg"
                		@size-change="getcxjg" />
                </div>
                
                <div class="cxdiv">
                    <el-button type="primary" native-type="submit" v-if="bgsx.kftb?.length && !bgsx.wytb" class="cxbutton" @click="toaddform(0)">新建填报</el-button>
                    <el-button type="primary" native-type="submit" class="cxbutton" @click="toback">返 回</el-button>
                </div>
			</div>
		</div>
	</div>
</div>
        `
    }